package com.xlserver.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xlserver.dao.ConsultationMapper;
import com.xlserver.dao.CounselorMapper;
import com.xlserver.dao.LoginInfoMapper;
import com.xlserver.dao.UserMapper;
import com.xlserver.domain.Consultation;
import com.xlserver.domain.Counselor;
import com.xlserver.domain.LoginInfo;
import com.xlserver.domain.User;
import com.xlserver.util.TimeUtil;
import com.xlserver.util.TokenUtil;
import com.xlserver.util.model.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Time;
import java.util.List;
import java.util.Map;
import java.util.Random;

@Service
public class UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    LoginInfoMapper loginInfoMapper;
    @Autowired
    TimeUtil timeUtil;
    @Autowired
    CounselorMapper counselorMapper;
    @Autowired
    ConsultationMapper consultationMapper;
    /**
     * 根据id判断是否有该用户
     */
    private boolean isUser(String phoneNum){
        return userMapper.selectByPhoneNum(phoneNum) != null;
    }

    public boolean checkPassword(int id, String password) {
        if (loginInfoMapper.selectById(id) == null){
            return false;
        }
        return password.equals(loginInfoMapper.selectById(id).getPassword());
    }
    //检验手机号是否重复，若重复返回true,反之返回false
    public boolean checkPhoneNum(String phoneNum){
        return userMapper.selectByPhoneNum(phoneNum) != null;
    }
//  个人信息：userid 姓名、手机号、紧急联系人、紧急电话、头像、性别、年龄 （参数名称，参数类型，参数说明）

    /**
     *根据phoneNum，password获取用户信息，登录使用的接口
     * 4:被禁用；3:登录成功；2：密码错误；1：无用户
     */
    public JSONObject getUserInfo(String phoneNum, String password){
        if(isUser(phoneNum)){
            User user = userMapper.selectByPhoneNum(phoneNum);
            int userId = user.getUserId();
            int isForbidden = user.getIsForbidden();
            //禁用
            if (isForbidden == 1){
                JSONObject ret = new JSONObject();
                ret.put("result", "4");
                ret.put("token", "");
                return ret;
            }
            //正常登录
            if (checkPassword(userId, password)) {
                //更新最近登录时间
                userMapper.update(null,new UpdateWrapper<User>()
                        .eq("uid",userId)
                        .set("uAccessDate",timeUtil.getDateTime()));
                JSONObject ret = JSONObject.parseObject(
                                    JSON.toJSON(
                                        userMapper.selectById(userId)).toString());
                ret.put("result","3");
                ret.put("token", TokenUtil.sign(""+userId, password));
                return ret;
            }
            else {//密码错误
                JSONObject ret = new JSONObject();
                ret.put("result", "2");
                ret.put("token", "");
                return ret;
            }
        }
        //无用户
        JSONObject ret = new JSONObject();
        ret.put("result", "1");
        ret.put("token", "");
        return ret;
    }
    /**
     * 根据userId，验证码获取用户信息
     */
    public JSONObject getUserInfoByCode(String phoneNum, String code){
        if (isUser(phoneNum)){
            User user = userMapper.selectByPhoneNum(phoneNum);
            int userId = user.getUserId();
            int isForbidden = user.getIsForbidden();
            //禁用
            if (isForbidden == 1){
                JSONObject ret = new JSONObject();
                ret.put("result", "4");
                ret.put("token", "");
                return ret;
            }//成功
            JSONObject ret = JSONObject.parseObject(
                                JSON.toJSON(
                                    userMapper.selectById(userId)).toString());
            ret.put("result","3");
            ret.put("token", TokenUtil.sign(""+userId, code));
            return ret;
        }
        else {//手机号错误
            JSONObject ret = new JSONObject();
            ret.put("result", "1");
            ret.put("token", "");
            return ret;
        }
    }

    /**
     *根据userId获取密码
     */
    public String getPassword(String userId) {
        LoginInfo info = loginInfoMapper.selectById(userId);
        return info == null ? "":info.getPassword();
    }
    //    姓名、认证过的手机号、紧急联系人、紧急联系人电话、密码、短信验证码（有个时间限制）
//    （参数名称，参数类型，是否必须，参数说明）

    /**
     *用户注册
     */
    public User register(UserInfo userInfo){
        User user = new User(userInfo);
        int id = setId();
        user.setUserId(id);
        loginInfoMapper.insert(new LoginInfo(id,userInfo.getPassword()));
        userMapper.insert(user);
        return userMapper.selectById(id);
    }

    /**
     *设置用户id，1 开头，五位数
     */
    private int setId(){
        String id = "1"+getRandom(4);
        while (userMapper.selectById(id)!=null){
            id="1"+getRandom(4);
        }
        return Integer.parseInt(id);
    }
    private String getRandom(int len) {
          Random r = new Random();
          StringBuilder rs = new StringBuilder();
          for (int i = 0; i < len; i++) {
                 rs.append(r.nextInt(10));
             }
          return rs.toString();
    }


    //userid、姓名、紧急联系人、紧急电话、性别、年龄
    //uid,uName,uGender
    //uEmergencyContactName,uEmergencyContactPhoneNumber
    //uAge
    /**
     *更新用户信息
     */
    public JSONObject updateUser(Map<String,String> info){
        int id = Integer.parseInt(info.get("uid"));
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("uid",id);
        for (Map.Entry<String, String> entry : info.entrySet()) {
            if (!"".equals(entry.getValue())){
                updateWrapper.set(entry.getKey(),entry.getValue());
            }
        }
        userMapper.update(null,updateWrapper);
        return JSONObject.parseObject(
                JSON.toJSON(
                        userMapper.selectById(id)).toString());
    }
    /**
     * 更新头像
     */
    public JSONObject updateAvatar(String avatar,int id){
        userMapper.update(null,new UpdateWrapper<User>()
                .eq("uid",id)
                .set("uProfilePhoto",avatar));
        JSONObject ret = new JSONObject();
        ret.put("avatar",avatar);
        return ret;
    }

    /**
     *更新密码
     */
    public JSONObject updatePassword(String userId, String password){
        int id = Integer.parseInt(userId);
        UpdateWrapper<LoginInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",id).set("password",password);
        loginInfoMapper.update(null,updateWrapper);
        JSONObject ret = new JSONObject();
        ret.put("res","success");
        return ret;
    }
    /**
     * 评价会话与咨询师
     */
    public JSONObject commend(int uid,int cid,double rank){
        //评价会话
        consultationMapper.update(null,new UpdateWrapper<Consultation>()
                .eq("cid",cid)
                .eq("uid",uid)
                .set("cRank",rank)
                .orderByDesc("h_endTime")
                .last("limit 1"));
        double average = consultationMapper.selectList(new QueryWrapper<Consultation>()
                .eq("cid",cid))
                .stream()
                .mapToDouble(Consultation::getCrank)
                .average()
                .orElse(0d);
        //咨询师评价更新
        counselorMapper.update(null,new UpdateWrapper<Counselor>()
                .eq("cid",cid)
                .set("cAverageGrade",average));
        JSONObject res = new JSONObject();
        res.put("result","success");
        return res;
    }
}
